﻿using System;
using System.Collections.Generic;
using System.Web;

namespace WxPayAPI
{
    public class NativePay
    {
        /**
        * 生成扫描支付模式一URL
        * @param productId 商品ID
        * @return 模式一URL
        */
        public string GetPrePayUrl(string productId)
        {
            Log.Info(this.GetType().ToString(), "Native pay mode 1 url is producing...");

            WxPayData data = new WxPayData();
            data.SetValue("appid", WxPayConfig.GetConfig().GetAppID());//公众帐号id
            data.SetValue("mch_id", WxPayConfig.GetConfig().GetMchID());//商户号
            data.SetValue("time_stamp", WxPayApi.GenerateTimeStamp());//时间戳
            data.SetValue("nonce_str", WxPayApi.GenerateNonceStr());//随机字符串
            data.SetValue("product_id", productId);//商品ID
            data.SetValue("sign", data.MakeSign());//签名
            string str = ToUrlParams(data.GetValues());//转换为URL串
            string url = "weixin://wxpay/bizpayurl?" + str;

            Log.Info(this.GetType().ToString(), "Get native pay mode 1 url : " + url);
            return url;
        }

        /**
        * 生成直接支付url，支付url有效期为2小时,模式二
        * @param productId 商品ID
        * @return 模式二URL
        */
        public string GetPayUrl(string productId)
        {
            Log.Info(this.GetType().ToString(), "Native pay mode 2 url is producing...");

            WxPayData data = new WxPayData();
            data.SetValue("body", "test");//商品描述
            data.SetValue("attach", "test");//附加数据
            data.SetValue("out_trade_no", WxPayApi.GenerateOutTradeNo());//随机字符串
            data.SetValue("total_fee", 1);//总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
            data.SetValue("goods_tag", "jjj");//商品标记
            data.SetValue("trade_type", "NATIVE");//交易类型
            data.SetValue("product_id", productId);//商品ID

            WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口
            string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接

            Log.Info(this.GetType().ToString(), "Get native pay mode 2 url : " + url);
            return url;
        }

        /**
        * 生成直接支付url，支付url有效期为2小时,模式二
        * @param productId 商品ID
        * @return prepay_id
        */
        public string GetPayUrl(string body, string attach, string out_trade_no, decimal totalFee)
        {
            WxPayData data = new WxPayData();
            data.SetValue("body", body);//商品描述
            data.SetValue("attach", attach);//附加数据
            data.SetValue("out_trade_no", out_trade_no);//随机字符串
            int total = (int)(totalFee * 100);
            data.SetValue("total_fee", total);//总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
            data.SetValue("trade_type", "APP");//交易类型
            //data.SetValue("product_id", 0);//商品ID

            WxPayData result = WxPayApi.UnifiedOrder(data);//调用统一下单接口
            string url = result.GetValue("code_url").ToString();//获得统一下单接口返回的二维码链接

            Log.Info(this.GetType().ToString(), "Get native pay mode 2 url : " + url);
            return url;
        }

        /**
    * 生成直接支付url，支付url有效期为2小时,模式二
    * @param productId 商品ID
    * @return prepay_id
    */
        public static string GetPayUrl2(string body, string detail, string out_trade_no, decimal totalFee)
        {
            WxPayData data = new WxPayData();
            data.SetValue("body", body);//商品描述
            data.SetValue("detail", detail.Replace(" ",""));//商品详情
            data.SetValue("out_trade_no", out_trade_no);//随机字符串
            int total = (int)(totalFee * 100);
            data.SetValue("total_fee", total);//总金额
            data.SetValue("time_start", DateTime.Now.ToString("yyyyMMddHHmmss"));//交易起始时间
            data.SetValue("time_expire", DateTime.Now.AddMinutes(10).ToString("yyyyMMddHHmmss"));//交易结束时间
            data.SetValue("trade_type", "APP");//交易类型

            WxPayData unifiedOrderResult = WxPayApi.UnifiedOrder(data);//调用统一下单接口
            string url = "";
            if (unifiedOrderResult.GetValue("return_code").ToString() == "SUCCESS")
            {
                url = GetAppApiParameters(unifiedOrderResult);
            }
            else
            {
                throw new Exception(unifiedOrderResult.GetValue("return_msg").ToString());
            }
            return url;
        }

        /**
         *  
         * 从统一下单成功返回的数据中获取App api支付所需的参数，
         * 微信浏览器调起JSAPI时的输入参数格式如下：
         * {
         *   "appId" : "wx2421b1c4370ec43b",     //公众号名称，由商户传入     
         *   "timeStamp":" 1395712654",         //时间戳，自1970年以来的秒数     
         *   "nonceStr" : "e61463f8efa94090b1f366cccfbbb444", //随机串     
         *   "package" : "prepay_id=u802345jgfjsdfgsdg888",     
         *   "signType" : "MD5",         //微信签名方式:    
         *   "paySign" : "70EA570631E4BB79628FBCA90534C63FF7FADD89" //微信签名 
         * }
         * @return string 微信浏览器调起AppApi时的输入参数，json格式可以直接做参数用
         * 更详细的说明请参考调起支付接口：https://pay.weixin.qq.com/wiki/doc/api/app/app.php?chapter=9_12&index=2
         * 
         */
        public static string GetAppApiParameters(WxPayData unifiedOrderResult)
        {

            //Log.Debug(this.GetType().ToString(), "JsApiPay::GetJsApiParam is processing...");

            WxPayData AppApiParam = new WxPayData();
            AppApiParam.SetValue("appid", WxPayConfig.GetConfig().GetAppID());
            AppApiParam.SetValue("partnerid", WxPayConfig.GetConfig().GetMchID());
            AppApiParam.SetValue("prepayid", unifiedOrderResult.GetValue("prepay_id"));
            AppApiParam.SetValue("package", "Sign=WXPay");
            AppApiParam.SetValue("noncestr", WxPayApi.GenerateNonceStr());
            AppApiParam.SetValue("timestamp", WxPayApi.GenerateTimeStamp());
            AppApiParam.SetValue("sign", AppApiParam.MakeSign());

            string parameters = AppApiParam.ToJson();

            //Log.Debug(this.GetType().ToString(), "Get jsApiParam : " + parameters);
            return parameters;
        }

        /**
        * 参数数组转换为url格式
        * @param map 参数名与参数值的映射表
        * @return URL字符串
        */
        private string ToUrlParams(SortedDictionary<string, object> map)
        {
            string buff = "";
            foreach (KeyValuePair<string, object> pair in map)
            {
                buff += pair.Key + "=" + pair.Value + "&";
            }
            buff = buff.Trim('&');
            return buff;
        }
    }
}